package com.ld.security.common.tomcat.util;

import cn.hutool.poi.excel.ExcelWriter;
import com.ld.security.common.core.util.JsonUtil;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

public class RespUtil {

	public static void setHeader(String key,String val){
		HttpServletResponse response = SessionUtil.getResponse();
		response.setHeader(key,val);
	}


	@SneakyThrows
	public static void sendRedirect(String url){
		HttpServletResponse response = SessionUtil.getResponse();
		response.sendRedirect(url);
	}

	@SneakyThrows
	private static void beforeDownFile(	HttpServletResponse response,String fileName ){
		String userAgent = SessionUtil.getHeader("User-Agent");
		//获取浏览器名（IE/Chome/firefox）
		if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
			//针对IE或IE为内核的浏览器
			fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
		}else {
			fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");//谷歌控制版本
		}

		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

	}


		@SneakyThrows
	public static void downloadFile(ExcelWriter excelWriter,String fileName) {

		HttpServletResponse response = SessionUtil.getResponse();
			beforeDownFile(response,fileName);


		OutputStream writer = response.getOutputStream();

		excelWriter.flush(writer);
		writer.close();
	}

		@SneakyThrows
	public static void downloadFile(InputStream outputStream,String fileName) {
		HttpServletResponse response = SessionUtil.getResponse();
		beforeDownFile(response,fileName);
		InputStream myStream =outputStream;
		OutputStream writer = response.getOutputStream();

		byte[] bs =  new byte[1024];
		int i = 0;
		while (i != -1){
			i = myStream.read(bs);
			writer.write(bs);
		}

		writer.flush();
		writer.close();

	}

	@SneakyThrows
  public static void downloadFile(File f) {
		InputStream myStream = new FileInputStream(f);
		downloadFile(myStream,f.getName());
  }

		@SneakyThrows
	public static void downloadFile(String name,byte[] bytes){
		HttpServletResponse response = SessionUtil.getResponse();
		response.setHeader("content-type", "application/octet-stream");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename=" + name);

		OutputStream writer = response.getOutputStream();

		writer.write(bytes);
		writer.flush();
		writer.close();
	}
	
	 public static void writeCookie(String cookieName,String value){
		 HttpServletResponse response = SessionUtil.getResponse();
		 Cookie cookie = new Cookie(cookieName,value);
	        cookie.setPath("/");
	        cookie.setMaxAge(1*24*60*60);
	        response.addCookie(cookie);
	    }





	 public static void writeJson(Object obj) {
		 HttpServletResponse response = SessionUtil.getResponse();
		 PrintWriter out = null;
	        try {
	        	String json;
	            response.setCharacterEncoding("UTF-8");
	            response.setContentType("application/json; charset=utf-8");
	            out = response.getWriter();
	            if(obj instanceof String){
	            	json=(String)obj;
				}else{
					json=JsonUtil.toJson(obj);
				}

	            out.write(json); 
	            out.flush();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	        	if(out != null) {
	        	    out.close();
	        	}
	           
	        }
	    }

	public static void writeHtml(String obj) {
		HttpServletResponse response = SessionUtil.getResponse();
		PrintWriter out = null;
		try {
			String json;
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=utf-8");
			out = response.getWriter();
			out.write(obj);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out != null) {
				out.close();
			}

		}
	}
	 /**
	  * 输出图片
	  * @param image
	 * @throws IOException 
	  */
	public static void writeImage(BufferedImage  image) {
		HttpServletResponse response = SessionUtil.getResponse();
		response.setDateHeader("Expires", 0);
		        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
		        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
		        response.setHeader("Pragma", "no-cache");  
		        response.setContentType("image/jpeg");  
		        ServletOutputStream out=null;
				try {
					out = response.getOutputStream();
					ImageIO.write(image, "JPEG", out);
				    out.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						if(out != null) {
							out.close();
						}
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
		}

}
